#!/usr/bin/env python

import os
from datetime import datetime
from google.appengine.api import memcache
from models.models import *
import json
import webapp2
from google.appengine.ext.webapp import template
import logging
import pprint
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers
import shortuuid


class MainHandler(webapp2.RequestHandler):
	def get(self):
		key = self.request.get("stars")
		fb_image = self.request.host_url + "/assets/images/earthhour-fb.png"
		template_obj = {
			'title': 'Earth hour - Skypad',
			'description' : 'Want to make your mark on the universe when the world switches off for Earth Hour?', 
			'url': self.request.url,
			'fb_image': fb_image
		}
		print key
		if key:
			print "KEY EXISTS"
			if len(key)==0:
				print "BUT THERE IS NOTHING ON IT"
				self.redirect("/error")
			try:
				# constellation = ndb.Key(urlsafe=key).get()
				constellation = ndb.Key(Constellation,key).get()

			except Exception:    
			    constellation = None
			
			if constellation is not None:
				blob_info = blobstore.BlobInfo.get(constellation.image_file).key()
				title = 'Earth hour - Skypad'
				description = "Constellation " + constellation.name + " created by " +constellation.username+ " for Earth Hour' sky pad. Want to make your own mark on the universe?"
				fb_image = self.request.host_url + "/img/" + str(blob_info)
				
				template_obj = {
					'title': title,
					'description' : description, 
					'url': self.request.url,
					'fb_image': fb_image
				}
				
				# path = os.path.join(os.path.dirname(__file__), '../views' ,'index.html')
				# self.response.out.write(template.render( path, template_obj))
			else:
				print 'no constellations, redirecting'
				self.redirect("/error")


		# We are using the template module to output the page.
		path = os.path.join(os.path.dirname(__file__), '../views' ,'index.html')
		self.response.out.write(template.render( path, template_obj))

class ShareHandler(webapp2.RequestHandler):
	def get(self, id):
		path = os.path.join(os.path.dirname(__file__), '../views' ,'share.html')
		self.response.out.write(template.render( path, template_obj))

class AdminHandler(webapp2.RequestHandler):
	def get(self):
		path = os.path.join(os.path.dirname(__file__), '../views' ,'admin.html')
		self.response.out.write(template.render( path, {}))

class ErrorHandler(webapp2.RequestHandler):
	def get(self):
		path = os.path.join(os.path.dirname(__file__), '../views' ,'error.html')
		self.response.out.write(template.render( path, {}))
		self.redirect("/")

			



class StarsHandler(webapp2.RequestHandler):
	""" Get all the stars
	"""
	def get(self):
		logging.debug('StarsHandler GET')
		response = [];
		all_stars = self.get_stars()
		for item in all_stars:
			w = item.to_dict()
			w['id'] = item.key.id()
			response.append(w)
		self.response.headers['Content-Type'] = 'application/json'
		self.response.out.write(json.dumps(response))

	def get_stars(self):
		stars = memcache.get('stars')
		response = []
		if not stars or stars is None:
			logging.debug('stars not in memcache - getting from datastore')
			stars = Star.query()
			
			for item in stars:
				response.append(item)


			if not memcache.add('stars', response):
				logging.error('Memcache set failed.')
			return response
		else:
			logging.debug('Stars stored in memcache - retrieving data')
			return stars

class ConstellationsHandler(webapp2.RequestHandler):
	""" Get all the Constellations
	"""
	def get(self, key):
		logging.debug('ConstellationsHandler GET')
		
		if key:
			
			constellation = ndb.Key(Constellation,key).get()
			o = {}
			o['id'] = constellation.key.id() 
			o['name'] = constellation.name 
			o['username'] = constellation.username 
			o['color'] = constellation.color
			blob_info = blobstore.BlobInfo.get(constellation.image_file).key()
			o['image_url'] = self.request.host_url + "/img/" + str(blob_info)
			o['url'] = self.request.host_url + "?stars=" + constellation.key.id() 
			o['stars'] = []
			for c in constellation.stars:	
				o['stars'].append(c.id())	
			response = o
		else:
			
			response = [];
			all_constellations = Constellation.query()
			for item in all_constellations:
				o = {}
				o['id'] = item.key.id()
				o['name'] = item.name 
				o['username'] = item.username 
				o['color'] = item.color 
				o['stars'] = []
				for c in item.stars:
					# print c.id()
					s = '=\r\n'.encode('unicode-escape').decode()
					# print s
					sid = c.id().encode('unicode-escape').decode()
					sid = sid.replace(s, '')
					# print sid
					o['stars'].append(sid)	
				response.append(o)

		self.response.headers['Content-Type'] = 'application/json'
		self.response.out.write(json.dumps(response))


class DeleteHandler(webapp2.RequestHandler):
	""" Get all the Constellations
	"""
	def delete(self, id):
		logging.debug('ConstellationsHandler GET')
		constellation = ndb.Key(Constellation,id)
		constellation.delete()
		self.response.out.write('200')

class AdminConstellationsHandler(webapp2.RequestHandler):
	""" Get all the Constellations
	"""
	def get(self):
		logging.debug('ConstellationsHandler GET')
		
		response = []
			
		all_constellations = Constellation.query()
		for item in all_constellations:
			o = {}
			o['id'] = item.key.id() 
			o['name'] = item.name 
			o['username'] = item.username 
			o['color'] = item.color
			blob_info = blobstore.BlobInfo.get(item.image_file).key()
			o['image_url'] = self.request.host_url + "/img/" + str(blob_info)
			o['url'] = self.request.host_url + "?stars=" + item.key.id() 
			response.append(o)
				

		self.response.headers['Content-Type'] = 'application/json'
		self.response.out.write(json.dumps(response))

class GetUploadURL(webapp2.RequestHandler):
	def get(self):
		upload_url = blobstore.create_upload_url('/upload')
		self.response.headers['Content-Type'] = 'application/json'
		self.response.out.write(json.dumps(upload_url))

class UploadHandler(blobstore_handlers.BlobstoreUploadHandler,webapp2.RequestHandler):
	""" upload all the Constellations
	"""
	def post(self):
		response = {}
		uuid = shortuuid.uuid()[:8]
		constellation = Constellation(id=uuid)
		constellation.name = self.request.get("name") 
		constellation.color = self.request.get("color")
		constellation.username = self.request.get("username")

	 	stars = self.request.get("stars")
	 	stars = stars.split(',')
	 	print stars
		for s in stars:
			print str(s)
			star = ndb.Key(Star,s)
			constellation.stars.append(star)

		upload = self.get_uploads()[0]
		constellation.image_file = upload.key()
		
		blob_info = blobstore.BlobInfo.get(constellation.image_file).key()
		key=constellation.put()
		response['name'] = self.request.get("name") 
		response['color'] = self.request.get("color") 
		response['username'] = self.request.get("username") 
		# response['stars'] = stars
		response['image_url'] = self.request.host_url + "/img/" + str(blob_info)
		response['url'] = self.request.host_url + "?stars=" + key.id()
		self.response.headers['Content-Type'] = 'application/json'
		self.response.out.write(json.dumps(response))


class ServeHandler(blobstore_handlers.BlobstoreDownloadHandler):
	def get(self, image_key):
    	# blobstore.get(audio_key)
		self.send_blob(image_key)

